import { RequestParams, ResponseData } from './http/http'
import base_url from './config';
import { useInformation } from '@/store/modules/index.ts'


const request = <T = any>(params : RequestParams) : Promise<ResponseData<T>> => {
	const { url, method = 'GET', data = {} } = params
	const header : Record<string, string> = {}
	const user = useInformation()

	if (method.toUpperCase() === 'POST') {
		header['Content-Type'] = 'application/json'
	}
	if (uni.getStorageSync("access_token").token) {
		header['Authorization'] = 'Bearer ' + uni.getStorageSync("access_token").token;
	}
	if (uni.getStorageSync("client_id")) {
		header['Clientid'] = uni.getStorageSync("client_id");
	} else {
		header['Clientid'] = '15f66758dac4c41d27d5eaaf97d7e188';
		uni.setStorageSync('client_id', header['Clientid'])
	}

	if (user.isExpired()) {
		user.clearUser()
	}
	
	return new Promise((resolve, reject) => {
		uni.request({
			url: base_url + url,
			method: method.toUpperCase() as UniApp.RequestOptions['method'],
			header: header,
			data: data,
			success: (response) => {
				const res = response.data as ResponseData<T>
				// 成功状态码
				if (res.code === 200) {
					resolve(res)
				} else if (res.code === 401) {
					uni.navigateTo({ url: '/pages/login/index' })
					user.clearUser()
					reject(res)
				}
				else {
					uni.showToast({
						icon: 'none',
						title: res.msg || '请求错误',
					})
					reject(res)
				}
			},
			fail: (err) => {
				uni.showToast({
					icon: 'none',
					title: '网络错误，换个网络试试',
				})
				reject(err)
			}
		})
	})
}

const uploadFile = <T = any>(url : string, filePath : string) : Promise<ResponseData<T>> => {
	return new Promise(function (resolve, reject) {
		uni.uploadFile({
			url: base_url + url, //请求接口地址
			filePath: filePath, //文件地址
			name: 'file',
			header: {
				'Authorization': 'Bearer '+ uni.getStorageSync("access_token").token,
				'Clientid': uni.getStorageSync("client_id") || '15f66758dac4c41d27d5eaaf97d7e188'
			},
			success: (response) => {
				try {
					const res : ResponseData<T> = typeof response.data === 'string' ? JSON.parse(response.data) : response.data;
					if (res.code === 200) {
						uni.showToast({
							icon: 'success',
							title: res.msg || '上传成功',
							duration: 1500
						});
						resolve(res);
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg || '上传失败',
							duration: 2000
						});
						resolve(res);
					}
				} catch (e) {
					uni.showToast({
						icon: 'none',
						title: '上传失败',
						duration: 2000
					});
					reject(e);
				}
			},
			fail: (err) => {
				uni.showToast({
					icon: 'error',
					title: "上传失败",
				})
				reject(err);
			}
		})
	})
}


export { request, uploadFile };